package cn.wolfcode.p2p.website.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import cn.wolfcode.p2p.base.domain.RealAuth;
import cn.wolfcode.p2p.base.domain.UserInfo;
import cn.wolfcode.p2p.base.exception.DisplayableException;
import cn.wolfcode.p2p.base.service.IRealAuthService;
import cn.wolfcode.p2p.base.service.IUserInfoService;
import cn.wolfcode.p2p.base.util.JSONResult;
import cn.wolfcode.p2p.base.util.UserContext;
import cn.wolfcode.p2p.website.util.UploadUtil;

/**
 * 前台实名认证相关
 * 
 * @author wolfcode
 *
 */
@Controller
public class RealAuthController {

	@Value("${app.imgfolder}")
	private String imgFolder;

	@Autowired
	private IUserInfoService userinfoService;

	@Autowired
	private IRealAuthService realAuthService;

	/**
	 * 身份证图片上传
	 */
	@RequestMapping("uploadImg")
	@ResponseBody
	public String uploadImg(MultipartFile file) {
		return "/upload/"+UploadUtil.upload(file, imgFolder);
	}

	/**
	 * 实名认证申请
	 */
	@RequestMapping("realAuth_save")
	@ResponseBody
	public JSONResult apply(RealAuth to) {
		JSONResult result = new JSONResult();
		try {
			this.realAuthService.apply(to);
		} catch (DisplayableException ex) {
			result = new JSONResult(false, ex.getMessage());
		} catch (Exception e) {
			// 把错误信息记录到服务器中日志文件中,方便排查问题.
			result = new JSONResult(false, "系统异常,请联系管理员!");
			e.printStackTrace();
		}
		return result;
	}

	/**
	 * 点击实名认证跳转到实名认证界面
	 */
	@RequestMapping("realAuth")
	public String realAuthPage(Model model) {
		UserInfo current = this.userinfoService.get(UserContext.getCurrent().getId());
		if (current.getHasRealAuth()) {
			// 审核通过
			model.addAttribute("realAuth", this.realAuthService.get(current.getRealAuthId()));
			return "realAuth_result";
		} else {
			if (current.getRealAuthId() == null) {
				// 如果没有实名认证且userinfo实名认证id为空,跳转到申请页面
				return "realAuth";
			} else {
				model.addAttribute("auditing", true);
				return "realAuth_result";
			}
		}
	}

}
